package com.miao.generator;

import freemarker.template.Configuration;
import freemarker.template.Template;
import freemarker.template.TemplateException;
import freemarker.template.TemplateExceptionHandler;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.io.FileWriter;
import java.io.IOException;
import java.io.Writer;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;

public class EntityGenerator implements GeneratorType {

    private static final Logger log = LoggerFactory.getLogger(EntityGenerator.class);

    @Override
    public void generator(String template, String url, Object params) throws IOException {
        Configuration configuration = new Configuration(Configuration.VERSION_2_3_31);
        configuration.setDefaultEncoding("UTF-8");
        configuration.setTemplateExceptionHandler(TemplateExceptionHandler.RETHROW_HANDLER);
        configuration.setLogTemplateExceptions(false);
        //根据string生成模板
        Template template1 = new Template("entity", template, configuration);
        System.out.println(template1);
        //确定生成路径存在
        Path path = PathHandel(url);
        //TODO: 这里需要处理输入package类哪些文件不需要生成，path只能对应到项目内目录，比如com.miao
        try (Writer fileWriter = new FileWriter(path.toFile())) {
            template1.process(params, fileWriter);
            System.out.println("文件生成成功: " + path.toAbsolutePath());
        } catch (TemplateException e) {
            throw new RuntimeException(e);
        }
    }

    /**
     * 路径处理
     *
     * @return
     */
    private Path PathHandel(String url) {
        //项目路径
        String property = System.getProperty("user.dir");
        String defaultPath = "\\src\\main\\java\\";
        String replace = url.replace(".", "\\");
        Path path = Paths.get(property + defaultPath + replace);
        try {
            Files.createDirectories(path.getParent());
        } catch (IOException e) {
            log.warn("文件创建失败");
            e.printStackTrace();
        }
        return path;
    }
}
